// 销售统计功能模块

// 全局变量
let jsonModal, jsonCloseBtn, copyBtn, jsonContent;
let orderDetailModal;

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化模态框元素
    initModalElements();
    
    // 初始化销售记录
    initSalesRecords();
    
    // 加载初始数据并更新UI
    const initialRecords = loadSalesRecords();
    updateSalesRecordsTable(initialRecords);
    updateStatisticsCards(calculateStatistics(initialRecords));
    drawRevenueChart(initialRecords);

    // 绑定事件监听器
    bindEventListeners();

    // 页面加载时自动应用默认日期筛选
    updateStatisticsByDateRange();
});

// 初始化模态框元素
function initModalElements() {
    jsonModal = document.getElementById('json-modal');
    jsonCloseBtn = document.querySelector('#json-modal .close-btn');
    copyBtn = document.getElementById('copyJsonBtn');
    jsonContent = document.getElementById('json-content');
    orderDetailModal = document.getElementById('order-detail-modal');

    if (!jsonModal || !jsonCloseBtn || !copyBtn || !jsonContent || !orderDetailModal) {
        console.error('无法找到必要的模态框元素');
    }
}

// 绑定事件监听器
function bindEventListeners() {
    // 日期选择器和查询按钮事件
    const dateFilter = document.getElementById('date-filter');
    if (dateFilter) dateFilter.addEventListener('change', updateStatisticsByDateRange);
    else console.error('未找到元素: date-filter');

    const filterBtn = document.getElementById('filter-btn');
    if (filterBtn) filterBtn.addEventListener('click', updateStatisticsByDateRange);
    else console.error('未找到元素: filter-btn');

    // 导出按钮事件
    const exportTodayXlsBtn = document.getElementById('export-today-xls-btn');
    if (exportTodayXlsBtn) exportTodayXlsBtn.addEventListener('click', exportTodaySalesRecordsAsXls);
    else console.error('未找到元素: export-today-xls-btn');

    const exportTodayJsonBtn = document.getElementById('export-today-json-btn');
    if (exportTodayJsonBtn) exportTodayJsonBtn.addEventListener('click', exportTodaySalesRecords);
    else console.error('未找到元素: export-today-json-btn');

    const exportAllXlsBtn = document.getElementById('export-all-xls-btn');
    if (exportAllXlsBtn) exportAllXlsBtn.addEventListener('click', exportAllRecordsAsXls);
    else console.error('未找到元素: export-all-xls-btn');

    // 批量导入按钮事件
    const batchImportBtn = document.getElementById('batch-import-btn');
    if (batchImportBtn) {
        batchImportBtn.addEventListener('click', function() {
            const batchImportFile = document.getElementById('batch-import-file');
            if (batchImportFile) batchImportFile.click();
            else console.error('未找到元素: batch-import-file');
        });
    } else {
        console.error('未找到元素: batch-import-btn');
    }

    // 文件选择事件
    const batchImportFile = document.getElementById('batch-import-file');
    if (batchImportFile) batchImportFile.addEventListener('change', handleBatchImport);
    else console.error('未找到元素: batch-import-file');


    // 模态框事件
    jsonCloseBtn.addEventListener('click', closeModal);
    copyBtn.addEventListener('click', copyJsonToClipboard);
    window.addEventListener('click', handleOutsideClick);

    // 订单详情表格事件委托
    const tableBody = document.getElementById('sales-records-body');
    if (tableBody) {
        tableBody.addEventListener('click', function(event) {
            if (event.target.classList.contains('view-details-btn')) {
                const index = parseInt(event.target.getAttribute('data-index'));
                const type = event.target.getAttribute('data-type');
                const records = loadSalesRecords();
                const filteredRecords = filterSalesRecordsByDate(records, document.getElementById('date-filter').value);
                const record = filteredRecords[index];
                if (record) {
                    if (type === 'json') {
                            // 显示JSON内容
                            if (jsonContent) {
                                jsonContent.textContent = JSON.stringify(record, null, 2);
                            }
                            // 显示模态框
                            if (jsonModal) {
                                jsonModal.style.display = 'block';
                            }
                        } else if (type === 'details') {
                            openOrderDetailModal(record);
                        }
                    }
                } else {
                    console.error('未找到指定的订单记录');
                }
            }
        );
    } else {
        console.error('未找到销售记录表体元素');
    }
}

// 处理批量导入
function handleBatchImport(event) {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    let importedCount = 0;
    let totalFiles = files.length;

    // 显示导入进度提示
    const progressModal = createProgressModal();
    updateProgressModal(progressModal, 0, totalFiles);

    console.log('开始导入', totalFiles, '个文件');

    // 逐个处理文件
    for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const fileExtension = file.name.split('.').pop().toLowerCase();

        console.log('处理文件:', file.name, '扩展名:', fileExtension);

        if (fileExtension === 'xls') {
            // 检查是否加载了SheetJS库
            if (typeof XLSX !== 'undefined') {
                console.log('SheetJS库已加载，开始解析文件');
                const reader = new FileReader();
                reader.onload = function(e) {
                    try {
                        const data = new Uint8Array(e.target.result);
                        console.log('文件加载完成，开始解析');
                        const workbook = XLSX.read(data, { type: 'array' });
                        // 假设我们只处理第一个工作表
                        const firstSheetName = workbook.SheetNames[0];
                        console.log('使用工作表:', firstSheetName);
                        const worksheet = workbook.Sheets[firstSheetName];
                        // 转换为JSON
                        const jsonData = XLSX.utils.sheet_to_json(worksheet);
                        console.log('解析得到', jsonData.length, '条原始记录');
                        // 格式化记录
                        const records = formatExcelRecords(jsonData);
                        console.log('格式化后得到', records.length, '条有效记录');
                        importBatchRecords(records);
                        importedCount++;
                        updateProgressModal(progressModal, importedCount, totalFiles);
                      } catch (error) {
                          console.error('导入Excel文件失败:', file.name, error);
                          // 显示更详细的错误信息
                          alert(`导入Excel文件 ${file.name} 时出错: ${error.message}\n\n详细信息:\n${error.stack}`);
                          importedCount++;
                          updateProgressModal(progressModal, importedCount, totalFiles);
                      }
                  };
                  reader.onerror = function(error) {
                      console.error('文件读取失败:', file.name, error);
                      alert(`读取文件 ${file.name} 时出错: ${error.message}`);
                      importedCount++;
                      updateProgressModal(progressModal, importedCount, totalFiles);
                  };
                  reader.readAsArrayBuffer(file);
              } else {
                  console.error('SheetJS库未加载');
                  alert('Excel文件导入需要SheetJS库支持。请确保已加载该库。');
                  importedCount++;
                  updateProgressModal(progressModal, importedCount, totalFiles);
              }
        } else {
            console.error('不支持的文件格式:', fileExtension);
            alert(`文件 ${file.name} 格式不支持，请上传XLS格式的文件`);
            importedCount++;
            updateProgressModal(progressModal, importedCount, totalFiles);
        }
    }

    // 重置文件输入，以便可以重复选择同一个文件
    event.target.value = '';
}

// 创建进度提示模态框
function createProgressModal() {
    // 检查是否已存在进度模态框
    let modal = document.getElementById('import-progress-modal');
    if (modal) {
        document.body.removeChild(modal);
    }

    modal = document.createElement('div');
    modal.id = 'import-progress-modal';
    modal.className = 'modal';
    modal.style.display = 'block';

    const modalContent = document.createElement('div');
    modalContent.className = 'modal-content';

    const title = document.createElement('h3');
    title.textContent = '数据导入进度';

    const progressContainer = document.createElement('div');
    progressContainer.className = 'progress-container';

    const progressBar = document.createElement('div');
    progressBar.className = 'progress-bar';
    progressBar.style.width = '0%';

    const progressText = document.createElement('p');
    progressText.className = 'progress-text';
    progressText.textContent = '0/0 文件';

    progressContainer.appendChild(progressBar);
    modalContent.appendChild(title);
    modalContent.appendChild(progressContainer);
    modalContent.appendChild(progressText);
    modal.appendChild(modalContent);
    document.body.appendChild(modal);

    return modal;
}

// 更新进度提示模态框
function updateProgressModal(modal, current, total) {
    const progressBar = modal.querySelector('.progress-bar');
    const progressText = modal.querySelector('.progress-text');

    if (progressBar && progressText) {
        const percentage = (current / total) * 100;
        progressBar.style.width = `${percentage}%`;
        progressText.textContent = `${current}/${total} 文件`;

        // 所有文件处理完成后关闭模态框
        if (current === total) {
            setTimeout(() => {
                modal.style.display = 'none';
                // 刷新数据显示
                const records = loadSalesRecords();
                updateSalesRecordsTable(records);
                updateStatisticsCards(calculateStatistics(records));
                drawRevenueChart(records);
                alert(`成功导入 ${total} 个文件的数据`);
            }, 1000);
        }
    }
}

// 格式化Excel记录
function formatExcelRecords(jsonData) {
    const records = [];

    jsonData.forEach(row => {
        // 尝试获取必要的字段
        const date = row.date || row.日期;
        // 兼容两种字段名格式：customerName、customer和客户名称
        const customerName = row.customerName || row.customer || row.客户名称;
        // 兼容products和商品字段
        let products = row.products || row.商品;

        if (date && customerName && products) {
            // 如果products是字符串
            if (typeof products === 'string') {
                // 尝试解析为JSON
                try {
                    products = JSON.parse(products);
                } catch (e) {
                    // 如果JSON解析失败，尝试解析导出的字符串格式
                    try {
                        products = parseProductString(products);
                    } catch (e2) {
                        console.error('解析商品数据失败:', row, e2);
                        return;
                    }
                }
            }

            // 确保products是数组
            if (!Array.isArray(products)) {
                console.error('商品数据不是数组:', row);
                return;
            }

            // 格式化记录
            const record = {
                date: date,
                customerName: customerName,
                products: products,
                totalAmount: parseFloat(row.totalAmount || row.金额 || 0)
            };

            records.push(record);
        }
    });

    return records;
}

// 解析导出的产品字符串格式
function parseProductString(productStr) {
    const products = [];
    // 匹配格式：商品名称(重量kg)
    const regex = /([^()]+)\((\d+(?:\.\d+)?)kg\)/g;
    let match;

    while ((match = regex.exec(productStr)) !== null) {
        const name = match[1].trim();
        const weight = parseFloat(match[2]);
        // 假设价格为0，实际使用时可能需要从其他地方获取
        products.push({ name, weight, price: 0 });
    }

    return products;
}

// 解析CSV数据
function parseCsvData(csvContent) {
    const lines = csvContent.split('\n');
    const headers = lines[0].split(',').map(header => header.trim());
    const records = [];

    console.log('CSV表头:', headers);
    console.log('CSV总行数:', lines.length);

    for (let i = 1; i < lines.length; i++) {
        if (lines[i].trim() === '') continue;

        const values = lines[i].split(',');
        const record = {};

        headers.forEach((header, index) => {
            if (index < values.length) {
                // 处理带引号的字段
                let value = values[index].trim();
                if (value.startsWith('"') && value.endsWith('"')) {
                    // 移除首尾引号
                    value = value.substring(1, value.length - 1);
                    // 处理双引号转义
                    value = value.replace(/""/g, '"');
                }
                record[header] = value;
            }
        });

        // 格式化记录数据
        // 兼容多种字段名格式
        const customerName = record.customerName || record.customer || record['客户名称'];
        const date = record.date || record['日期'];
        const products = record.products || record['商品'] || record['产品'];
        const totalAmount = record.totalAmount || record['总金额'] || record['金额'];

        if (date && customerName && products) {
            record.date = date;
            record.customerName = customerName;
            record.totalAmount = parseFloat(totalAmount) || 0;
            try {
                // 尝试解析为JSON
                record.products = JSON.parse(products);
                records.push(record);
            } catch (e) {
                console.error('解析产品数据失败:', e);
                console.error('产品字段值:', products);
                // 尝试处理简单格式的产品数据
                try {
                    // 处理"商品名称(重量kg)"格式
                        if (products.includes('(') && products.includes(')')) {
                            // 修改正则表达式以支持负数重量
                            const match = products.match(/(.+)\((-?\d+(?:\.\d+)?)kg\)/);
                            if (match) {
                                const name = match[1].trim();
                                const weight = parseFloat(match[2]);
                                
                                // 检查重量是否有效
                                if (!isNaN(weight) && weight !== 0) {
                                    // 计算单价
                                    const price = record.totalAmount / weight;
                                    record.products = [{ name, weight, price }];
                                    records.push(record);
                                    console.log('成功转换简单格式产品:', record.products);
                                } else {
                                    console.error('无效的产品重量:', weight);
                                    console.error('完整产品字段值:', products);
                                }
                            } else {
                                console.error('无法匹配产品格式:', products);
                                // 输出更多上下文信息帮助调试
                                console.error('完整记录:', record);
                            }
                        } 
                    // 处理可能的其他格式...
                    else {
                        console.error('无法识别的产品格式:', products);
                    }
                } catch (e2) {
                    console.error('转换产品格式失败:', e2);
                    console.error('完整记录:', record);
                }
            }
        } else {
            console.log('跳过无效记录(缺少必填字段):', record);
            if (!date) console.log('- 日期');
            if (!customerName) console.log('- 客户名称');
            if (!products) console.log('- 产品');
        }
    }

    console.log('成功解析的记录数:', records.length);
    return records;
}

// 导入批量记录
function importBatchRecords(records) {
    if (records.length === 0) {
        alert('没有找到有效的记录');
        return;
    }

    // 加载现有记录
    const existingRecords = loadSalesRecords();

    // 去重处理（假设每条记录有唯一ID或可以通过日期+客户+商品组合判断）
    const newRecords = records.filter(newRecord => {
        return !existingRecords.some(existing => 
            existing.date === newRecord.date && 
            existing.customerName === newRecord.customerName &&
            JSON.stringify(existing.products) === JSON.stringify(newRecord.products)
        );
    });

    if (newRecords.length === 0) {
        alert('没有新记录导入');
        return;
    }

    // 合并记录
    const updatedRecords = [...existingRecords, ...newRecords];
    localStorage.setItem('salesRecords', JSON.stringify(updatedRecords));

    // 更新UI
    updateSalesRecordsTable(updatedRecords);
    updateStatisticsCards(calculateStatistics(updatedRecords));
    drawRevenueChart(updatedRecords);

    alert(`成功导入 ${newRecords.length} 条记录`);
};

// 从本地存储加载销售记录
function loadSalesRecords() {
    try {
        const salesRecordsJson = localStorage.getItem('salesRecords') || '[]';
        const records = JSON.parse(salesRecordsJson);
        // 验证数据格式
        if (!Array.isArray(records)) {
            throw new Error('销售记录格式不正确');
        }
        console.log('加载的销售记录数量: ' + records.length);
        return records;
    } catch (e) {
        console.error('加载销售记录失败:', e);
        // 重置损坏的数据
        saveSalesRecords([]);
        return [];
    }
}

// 保存销售记录到本地存储
function saveSalesRecords(records) {
    localStorage.setItem('salesRecords', JSON.stringify(records));
}
function initSalesRecords() {
    // 初始化商品成本价
    if (!localStorage.getItem('productCostPrices')) {
        const defaultCostPrices = {
            
        };
        localStorage.setItem('productCostPrices', JSON.stringify(defaultCostPrices));
        console.log('已初始化默认商品成本价');
    }

    // 初始化销售记录
    if (!localStorage.getItem('salesRecords')) {
        // 添加示例销售记录
        
        saveSalesRecords(sampleRecords);
        console.log('已初始化示例销售记录');
    }

    // 添加退货相关样式
    const style = document.createElement('style');
    style.textContent = `
        /* 退货相关样式 */
        .return-order { background-color: #fff0f0; }
        .return-product { color: #e74c3c; font-weight: bold; }
        .return-price { color: #e74c3c; }
    `;
    document.head.appendChild(style);
}
// 初始化销售记录（如果不存在）


// 根据日期范围过滤销售记录
function filterSalesRecordsByDate(records, dateRange) {
    const now = new Date();
    let startDate, endDate;

    switch (dateRange) {
        case 'today':
            startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
            break;
        case 'yesterday':
            startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
            endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
            break;
        case 'week':
            startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay());
            endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
            break;
        case 'month':
            startDate = new Date(now.getFullYear(), now.getMonth(), 1);
            endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1);
            break;
        case 'all':
            return records;
        default:
            console.error('未知的日期范围: ' + dateRange);
            return records;
    }

    return records.filter(record => {
        const recordDate = new Date(record.date);
        return recordDate >= startDate && recordDate < endDate;
    });
}

// 计算统计信息
function calculateStatistics(records) {
      const totalRevenue = records.reduce((sum, record) => sum + record.totalAmount, 0);
      const totalOrders = records.length;
      
      // 计算客单价
      const avgOrderAmount = totalOrders > 0 ? totalRevenue / totalOrders : 0;
      
      // 从localStorage加载商品成本价
      const productCostPrices = JSON.parse(localStorage.getItem('productCostPrices')) || {};
      console.log('加载的成本价数据:', productCostPrices);
      console.log('成本价数据数量:', Object.keys(productCostPrices).length);
      // 打印部分关键商品的成本价
      console.log('排骨成本价:', productCostPrices['排骨'] || '未找到');
      console.log('五花肉成本价:', productCostPrices['五花肉'] || '未找到');
      
      // 计算实际总利润
      let totalProfit = 0;
      let missingCostCount = 0;
      let missingCostProducts = [];
      let returnAmount = 0; // 退货总金额
    records.forEach(record => {
        record.products.forEach(product => {
            // 优先使用商品记录中的成本价，如果没有则使用全局成本价数据
            const costPrice = product.costPrice || productCostPrices[product.name] || 0;
            if (costPrice === 0) {
                missingCostCount++;
                if (!missingCostProducts.includes(product.name)) {
                    missingCostProducts.push(product.name);
                }
            }
            // 确保价格和重量是有效的数字
            const price = parseFloat(product.price) || 0;
            const weight = parseFloat(product.weight) || 0;
            const productProfit = (price - costPrice) * weight;
            // 打印每个商品的利润计算详情
            console.log(`商品: ${product.name}, 价格: ${price}, 成本价: ${costPrice}, 重量: ${weight}, 利润: ${productProfit}`);
            totalProfit += productProfit;
            
            // 统计退货金额
            if (price < 0) {
                returnAmount += price * weight;
            }
        });
    });
    
    console.log('退货总金额:', returnAmount);

    console.log('总利润计算结果:', totalProfit);
    console.log('缺少成本价的商品数量:', missingCostCount);
    console.log('缺少成本价的商品列表:', missingCostProducts);

    console.log('缺少成本价的商品数量:', missingCostCount);
    console.log('缺少成本价的商品列表:', missingCostProducts);
    
    return {
        totalRevenue,
        totalOrders,
        avgOrderAmount,
        totalProfit,
        returnAmount // 添加退货金额
    };
}


// 更新统计卡片
function updateStatisticsCards(statistics) {
    const totalRevenueEl = document.getElementById('total-revenue');
    const totalOrdersEl = document.getElementById('total-orders');
    const avgOrderAmountEl = document.getElementById('avg-order-amount');
    const totalProfitEl = document.getElementById('total-profit');
    const returnAmountEl = document.getElementById('return-amount');
    
    if (totalRevenueEl) totalRevenueEl.textContent = statistics.totalRevenue.toFixed(2);
    if (totalOrdersEl) totalOrdersEl.textContent = statistics.totalOrders;
    if (avgOrderAmountEl) avgOrderAmountEl.textContent = statistics.avgOrderAmount.toFixed(2);
    if (totalProfitEl) totalProfitEl.textContent = statistics.totalProfit.toFixed(2);
    if (returnAmountEl) {
        returnAmountEl.textContent = statistics.returnAmount.toFixed(2);
        // 如果有退货，显示红色
        if (statistics.returnAmount < 0) {
            returnAmountEl.style.color = 'red';
        } else {
            returnAmountEl.style.color = '';
        }
    }
}

// 更新统计数据的函数
function updateStatisticsByDateRange() {
    const dateRange = document.getElementById('date-filter').value;
    const allRecords = loadSalesRecords();
    const filteredRecords = filterSalesRecordsByDate(allRecords, dateRange);
    
    updateSalesRecordsTable(filteredRecords);
    updateStatisticsCards(calculateStatistics(filteredRecords));
    drawRevenueChart(filteredRecords);
}

// 删除销售记录
function deleteSalesRecord(index) {
    if (confirm('确定要删除这条销售记录吗？')) {
        const records = loadSalesRecords();
        const filteredRecords = filterSalesRecordsByDate(records, document.getElementById('date-filter').value);
        const recordToDelete = filteredRecords[index];

        // 从所有记录中找到并删除
        const updatedRecords = records.filter(record => {
            return !(record.date === recordToDelete.date && 
                   record.customerName === recordToDelete.customerName && 
                   JSON.stringify(record.products) === JSON.stringify(recordToDelete.products));
        });

        saveSalesRecords(updatedRecords);
        alert('销售记录已删除');

        // 更新UI
        updateSalesRecordsTable(filterSalesRecordsByDate(updatedRecords, document.getElementById('date-filter').value));
        updateStatisticsCards(calculateStatistics(updatedRecords));
        drawRevenueChart(updatedRecords);
    }
}

// 批量删除指定客户的所有销售记录
function batchDeleteCustomerRecords(customerNames) {
    if (!Array.isArray(customerNames) || customerNames.length === 0) {
        alert('请提供要删除的客户名称列表');
        return;
    }

    if (confirm(`确定要删除以下客户的所有销售记录吗？\n${customerNames.join('\n')}`)) {
        const records = loadSalesRecords();
        // 过滤掉指定客户的记录
        const updatedRecords = records.filter(record => {
            return !customerNames.includes(record.customerName);
        });

        const deletedCount = records.length - updatedRecords.length;
        saveSalesRecords(updatedRecords);
        alert(`成功删除 ${deletedCount} 条销售记录`);

        // 更新UI
        const dateFilter = document.getElementById('date-filter').value;
        updateSalesRecordsTable(filterSalesRecordsByDate(updatedRecords, dateFilter));
        updateStatisticsCards(calculateStatistics(updatedRecords));
        drawRevenueChart(updatedRecords);
    }
}

// 删除示例客户记录的快捷函数
function deleteSampleCustomerRecords() {
    batchDeleteCustomerRecords(['示例客户1', '示例客户2']);
}

// 更新销售记录表格
function updateSalesRecordsTable(records) {
    const tableBody = document.getElementById('sales-records-body');
    if (!tableBody) {
        console.error('未找到销售记录表体元素');
        return;
    }
    
    tableBody.innerHTML = '';

    if (records.length === 0) {
        // 显示无数据提示
        const emptyRow = document.createElement('tr');
        emptyRow.innerHTML = '<td colspan="6" style="text-align: center;">暂无销售记录</td>';
        tableBody.appendChild(emptyRow);
    } else {
        records.forEach((record, index) => {
            const date = new Date(record.date).toLocaleString();
            // 计算订单利润和检查是否为退货订单
            const productCostPrices = JSON.parse(localStorage.getItem('productCostPrices')) || {};
            let orderProfit = 0;
            let isReturnOrder = false;
            record.products.forEach(product => {
                const costPrice = product.costPrice || productCostPrices[product.name] || 0;
                const price = parseFloat(product.price);
                const weight = parseFloat(product.weight);
                const productProfit = (price - costPrice) * weight;
                orderProfit += productProfit;
                // 添加单个商品的利润信息
                product.profit = productProfit.toFixed(2);
                
                // 检查是否为退货商品
                if (price < 0) {
                    isReturnOrder = true;
                }
            });

            // 创建商品列表HTML
            const productsList = record.products.map(p => {
                const isReturnProduct = parseFloat(p.price) < 0;
                return `<span class="${isReturnProduct ? 'return-product' : ''}">${p.name}(${p.weight}kg)</span>`;
            }).join(', ');

            const row = document.createElement('tr');
            // 如果是退货订单，添加特殊样式
            if (isReturnOrder) {
                row.classList.add('return-order');
            }
            // 检查是否有备注
            const hasRemarks = record.remarks && record.remarks.length > 0;
            const remarksCount = hasRemarks ? record.remarks.length : 0;
            // 将订单总利润添加到record对象，以便JSON查看时显示
            record.profit = orderProfit.toFixed(2);

            row.innerHTML = `
                <td>${date}</td>
                <td>${record.customerName}</td>
                <td>${productsList}</td>
                <td>${record.totalAmount.toFixed(2)}</td>
                <td>${orderProfit.toFixed(2)}</td>
                <td>
                    <div class="actions">
                        <button class="view-details-btn" data-index="${index}" data-type="details">查看详情</button>
                        <button class="view-details-btn" data-index="${index}" data-type="json">JSON查看</button>
                        <button class="delete-record-btn" data-index="${index}">删除</button>
                    </div>
                </td>
                <td>
                    备注: ${remarksCount} 条
                </td>
            `;

            tableBody.appendChild(row);
        });
    }

    // 为删除按钮添加事件监听器
    document.querySelectorAll('.delete-record-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const index = parseInt(this.getAttribute('data-index'));
            deleteSalesRecord(index);
        });
    });
}

// 导出今日销售记录为JSON
function exportTodaySalesRecords() {
    const records = loadSalesRecords();
    console.log('总销售记录数:', records.length);
    const todayRecords = filterSalesRecordsByDate(records, 'today');
    console.log('今日销售记录数:', todayRecords.length);

    // 检查今日记录是否为空
    if (todayRecords.length === 0) {
        console.log('触发订单为空提示');
        alert('订单为空');
        return;
    }

    // 显示JSON内容
    if (jsonContent) {
        jsonContent.textContent = JSON.stringify(todayRecords, null, 2);
    }

    // 显示模态框
    if (jsonModal) {
        jsonModal.style.display = 'block';
    }
}

// 导出销售记录为表格、CSV或XLS
function exportSalesRecordsAsTable(records, filename, format = 'html') {
    if (records.length === 0) {
        alert('没有找到可导出的销售记录');
        return;
    }

    let content, mimeType, extension;

    if (format === 'csv') {
        // 创建CSV内容(查看格式)
        let csvContent = '日期,客户名称,产品,总金额,利润\n';

        records.forEach(record => {
            const date = new Date(record.date).toLocaleString();
            const customerName = record.customerName.replace(/,/g, ''); // 移除逗号
            const productsList = record.products.map(p => `${p.name}(${p.weight}kg)`).join('; ');
            const totalAmount = record.totalAmount.toFixed(2);

            // 计算利润
            const productCostPrices = JSON.parse(localStorage.getItem('productCostPrices')) || {};
            let profit = 0;
            record.products.forEach(product => {
                const costPrice = productCostPrices[product.name] || 0;
                const productProfit = (product.price - costPrice) * product.weight;
                profit += productProfit;
            });

            csvContent += `${date},${customerName},${productsList},${totalAmount},${profit.toFixed(2)}\n`;
        });

        content = csvContent;
        mimeType = 'text/csv';
        extension = 'csv';
    } else if (format === 'import_csv') {
            // 创建CSV内容(导入格式)
            // 确保包含正确的标题行，parseCsvData函数依赖于此
            let csvContent = 'date,customerName,products,totalAmount\n';

        records.forEach(record => {
            // 使用与导入兼容的日期格式
            const date = record.date;
            const customerName = record.customerName.replace(/,/g, ''); // 移除逗号
            // 产品转为JSON字符串，并替换双引号为两个双引号以符合CSV格式
            const productsJson = JSON.stringify(record.products).replace(/"/g, '""');
            const totalAmount = record.totalAmount.toFixed(2);
            
            // 构建CSV行
            csvContent += `${date},"${customerName}","${productsJson}",${totalAmount}\n`;
        });
        
        content = csvContent;
        mimeType = 'text/csv';
        extension = 'csv';
    } else if (format === 'xls') {
        // 创建XLS内容（符合导入格式）
        // 准备工作表数据，使用与导入兼容的字段名
        const wsData = [['date', 'customerName', 'products', 'totalAmount']];
        
        records.forEach(record => {
            // 使用与导入兼容的日期格式 (YYYY-MM-DD)
            const date = record.date;
            const customerName = record.customerName;
            
            // 产品转为JSON字符串，确保格式与导入要求一致
            const productsJson = JSON.stringify(record.products);
            const totalAmount = record.totalAmount.toFixed(2);

            wsData.push([date, customerName, productsJson, totalAmount]);
        });

        // 创建工作簿和工作表
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(wsData);
        XLSX.utils.book_append_sheet(wb, ws, '销售记录');

        // 生成XLS文件
        content = XLSX.write(wb, { bookType: 'xls', type: 'binary' });
        mimeType = 'application/vnd.ms-excel';
        extension = 'xls';
        
        // 转换二进制字符串为Uint8Array
        const buf = new ArrayBuffer(content.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i < content.length; i++) {
            view[i] = content.charCodeAt(i) & 0xFF;
        }
        content = buf;
    }

    // 确保文件名有正确的扩展名
    if (!filename || !filename.endsWith('.' + extension)) {
        filename = filename ? filename.replace(/\.[^/.]+$/, '') + '.' + extension : 'sales-records.' + extension;
    }

    // 创建Blob对象
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);

    // 创建下载链接
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();

    // 清理
    setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }, 0);
}



// 格式化日期为YYYY-MM-DD格式，用于文件名
function formatDateForFilename(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}



    // 显示模态框
    if (jsonModal) {
        jsonModal.style.display = 'block';
    }
// 由于单独的 `}` 无法构成有效声明或语句，且从上下文推测可能是文件结束多余的字符，此处移除该字符。



// 直接导出今日销售记录为XLS
function exportTodaySalesRecordsAsXls() {
    const today = new Date();
    const formattedDate = formatDateForFilename(today);
    const records = loadSalesRecords();
    const todayRecords = filterSalesRecordsByDate(records, 'today');
    exportSalesRecordsAsTable(
        todayRecords,
        `${formattedDate}`,
        'xls'
    );
}

// 直接导出所有销售记录为XLS
function exportAllRecordsAsXls() {
    const today = new Date();
    const formattedDate = formatDateForFilename(today);
    const records = loadSalesRecords();
    exportSalesRecordsAsTable(
        records,
        `${formattedDate}-all`,
        'xls'
    );
}

// 直接导出所有销售记录为CSV(导入格式)
function exportAllRecordsAsCsv() {
    const today = new Date();
    const formattedDate = formatDateForFilename(today);
    const records = loadSalesRecords();
    exportSalesRecordsAsTable(
        records,
        `${formattedDate}-all-import`,
        'import_csv'
    );
}

// 导出今日销售记录为导入格式CSV
function exportTodaySalesRecordsAsImportCsv() {
    const today = new Date();
    const formattedDate = formatDateForFilename(today);
    const records = loadSalesRecords();
    const todayRecords = filterSalesRecordsByDate(records, 'today');
    exportSalesRecordsAsTable(
        todayRecords,
        `${formattedDate}-import`,
        'import_csv'
    );
}

// 直接导出所有销售记录为导入格式CSV
function exportAllRecordsAsImportCsv() {
    const today = new Date();
    const formattedDate = formatDateForFilename(today);
    const records = loadSalesRecords();
    exportSalesRecordsAsTable(
        records,
        `${formattedDate}-import`,
        'import_csv'
    );
}

// 复制JSON内容到剪贴板
function copyJsonToClipboard() {
    // 使用全局变量jsonContent
    if (jsonContent && jsonContent.textContent) {
        navigator.clipboard.writeText(jsonContent.textContent)
            .then(() => {
                alert('JSON内容已复制到剪贴板');
            })
            .catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制');
            });
    } else {
        alert('没有可复制的内容');
    }
}

// 关闭模态框
function closeModal() {
    if (jsonModal) {
        jsonModal.style.display = 'none';
    }
}

// 处理模态框外部点击
function handleOutsideClick(event) {
    if (event.target === jsonModal) {
        closeModal();
    }
}

// 打开订单详情模态框
function openOrderDetailModal(record) {
    // 实现订单详情模态框功能
    const orderDetailContent = document.getElementById('order-detail-content');
    if (!orderDetailContent || !orderDetailModal) {
        console.error('未找到订单详情模态框元素');
        return;
    }

    // 格式化日期
    const date = new Date(record.date).toLocaleString();

    // 计算订单利润和退货金额
    const productCostPrices = JSON.parse(localStorage.getItem('productCostPrices')) || {};
    let orderProfit = 0;
    let orderReturnAmount = 0;
    record.products.forEach(product => {
        const costPrice = product.costPrice || productCostPrices[product.name] || 0;
        const price = parseFloat(product.price);
        const weight = parseFloat(product.weight);
        const productProfit = (price - costPrice) * weight;
        orderProfit += productProfit;
        // 添加单个商品的利润信息
        product.profit = productProfit.toFixed(2);
        
        // 统计退货金额
        if (price < 0) {
            orderReturnAmount += price * weight;
        }
    });
    // 将订单总利润添加到record对象
    record.profit = orderProfit.toFixed(2);
    record.returnAmount = orderReturnAmount;

    // 创建订单详情HTML
    let detailHtml = `
        <h3>订单详情</h3>
        <p><strong>日期:</strong> ${date}</p>
        <p><strong>客户名称:</strong> ${record.customerName}</p>
        <p><strong>总金额:</strong> ${record.totalAmount.toFixed(2)}</p>
        <p><strong>总利润:</strong> ${record.profit || '0.00'}</p>
        <p><strong>退货金额:</strong> ${record.returnAmount ? `<span class="return-price">${record.returnAmount.toFixed(2)}</span>` : '0.00'}</p>
        <h4>产品列表</h4>
        <table border="1" width="100%">
            <thead>
                <tr>
                    <th>产品名称</th>
                    <th>单价</th>
                    <th>重量(kg)</th>
                    <th>金额</th>
                    <th>利润</th>
                </tr>
            </thead>
            <tbody>
    `;

    record.products.forEach(product => {
        detailHtml += `
                <tr>
                    <td>${product.name}</td>
                    <td>${product.price.toFixed(2)}</td>
                    <td>${product.weight}</td>
                    <td>${product.amount.toFixed(2)}</td>
                    <td>${product.profit || '0.00'}</td>
                </tr>
        `;
    });

    detailHtml += `
            </tbody>
        </table>
    `;

    // 添加备注表格
    detailHtml += `
        <h4>备注信息</h4>
    `;

    if (record.remarks && record.remarks.length > 0) {
        detailHtml += `
        <table border="1" width="100%">
            <thead>
                <tr>
                    <th>备注日期</th>
                    <th>备注内容</th>
                </tr>
            </thead>
            <tbody>
        `;

        record.remarks.forEach(remark => {
            const remarkDate = new Date(remark.date).toLocaleString();
            detailHtml += `
                <tr>
                    <td>${remarkDate}</td>
                    <td>${remark.content}</td>
                </tr>
            `;
        });

        detailHtml += `
            </tbody>
        </table>
        `;
    } else {
        detailHtml += `<p>暂无备注信息</p>`;
    }

    // 设置内容并显示模态框
    orderDetailContent.innerHTML = detailHtml;
    orderDetailModal.style.display = 'block';

    // 绑定关闭按钮事件
    const orderDetailCloseBtn = document.querySelector('#order-detail-modal .close-btn');
    if (orderDetailCloseBtn) {
        // 先移除可能存在的事件监听器
        orderDetailCloseBtn.removeEventListener('click', closeOrderDetailModal);
        // 再添加新的事件监听器
        orderDetailCloseBtn.addEventListener('click', closeOrderDetailModal);
    }
}

// 关闭订单详情模态框
function closeOrderDetailModal() {
    if (orderDetailModal) {
        orderDetailModal.style.display = 'none';
    }
}

// 绘制收入图表
function drawRevenueChart(records) {
    const ctx = document.getElementById('revenue-chart');
    if (!ctx) {
        console.error('未找到图表画布元素');
        return;
    }

    // 检查Chart是否已加载
    if (typeof Chart === 'undefined') {
        console.error('Chart.js 未加载');
        ctx.parentElement.innerHTML = '<p style="color: red;">图表加载失败: 未找到Chart.js</p>';
        return;
    }

    // 按日期分组统计收入
    const revenueByDate = {};
    records.forEach(record => {
        const dateKey = new Date(record.date).toLocaleDateString();
        if (!revenueByDate[dateKey]) {
            revenueByDate[dateKey] = 0;
        }
        revenueByDate[dateKey] += record.totalAmount;
    });

    // 准备图表数据
    const labels = Object.keys(revenueByDate).sort();
    const data = labels.map(date => revenueByDate[date]);

    // 销毁旧图表（如果存在）
    if (window.revenueChartInstance) {
        window.revenueChartInstance.destroy();
    }

    // 创建新图表
    window.revenueChartInstance = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: '每日收入',
                data: data,
                backgroundColor: 'rgba(75, 192, 192, 0.6)',
                borderColor: 'rgba(75, 192, 192, 1)',
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return '¥' + value.toFixed(2);
                        }
                    }
                }
            },
            plugins: {
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return '收入: ¥' + context.parsed.y.toFixed(2);
                        }
                    }
                }
            }
        }
    });
}

